package cn.clementine.core.api;

import cn.clementine.core.entity.file.FileInfo;
import cn.clementine.core.utils.FileUtil;
import cn.clementine.core.vo.Result;
import cn.clementine.core.vo.cloudStorage.InitInfo;
import cn.dev33.satoken.annotation.SaCheckLogin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static cn.clementine.core.utils.FileUtil.isFileGreaterThan10MB;

@SaCheckLogin
@RestController
@RequestMapping("/cloud_storage")
@Slf4j
public class FileApi {
    @GetMapping("/initialize")
    public Result initialize(){
        return Result.ok(new InitInfo(System.getProperty("user.home") + File.separator + "Desktop"));
    }
    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        File dest = new File("path/to/your/directory" + fileName);
        try {
            file.transferTo(dest);
            return "File uploaded successfully!";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "Uploading failed!";
    }
    @GetMapping("/download")
    public ResponseEntity<org.springframework.core.io.Resource> serveFile(@RequestParam String dir_path,@RequestParam String filename) {
        if(dir_path.charAt(dir_path.length()-1)!='/') dir_path+='/';
        org.springframework.core.io.Resource file = new FileSystemResource(dir_path + filename);
        return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                "attachment; filename=\"" + file.getFilename() + "\"").body(file);
    }
    @PostMapping("/get_content")
    public Result getContent(@RequestBody Map<String, String> requestBody){
        try{
            String dir_path = requestBody.get("dir_path");
            String file_name = requestBody.get("file_name");
            if(dir_path.charAt(dir_path.length()-1)!='/') dir_path+='/';
            if(isFileGreaterThan10MB(dir_path + file_name)){
                return Result.fail("文件太大了，超过10MB,打不开");
            };
            return Result.ok(FileUtil.readFileContent(dir_path + file_name));
        }catch (IOException e){
            return Result.fail("文件被移动或者没有这个文件/权限不够！");
        }
    }
    @DeleteMapping("/delete/{filename:.+}")
    public String deleteFile(@PathVariable String filename) {
        File file = new File("path/to/your/directory" + filename);
        if (file.delete()) {
            return "File deleted successfully!";
        } else {
            return "Deleting failed!";
        }
    }
    @GetMapping("/files")
    public Result listFiles(@RequestParam String dir_path) {
        File folder = new File(dir_path);
        File[] listOfFiles = folder.listFiles();
        List<FileInfo> files = new ArrayList<>();
        if(listOfFiles == null){
            return Result.fail("没这个路径！");
        };
        for (File file : listOfFiles) {
            FileInfo fileInfo = new FileInfo();
            fileInfo.setName(file.getName());
            fileInfo.setSize(file.length());
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime lastModifiedDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(file.lastModified()), ZoneId.systemDefault());
            String formattedLastModified = lastModifiedDateTime.format(formatter);
            fileInfo.setLastModified(formattedLastModified);
            fileInfo.setDirectory(file.isDirectory());
            // 获取文件权限
            boolean canRead = file.canRead();
            boolean canWrite = file.canWrite();
            boolean canExecute = file.canExecute();
            fileInfo.setPermissions(String.format("%s,%s,%s", canRead, canWrite, canExecute));
            files.add(fileInfo);
        }
        return Result.ok(files);
    }
}
